package com.ican.action.user;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ican.common.BusinessException;
import com.ican.common.hibernate.Page;
import com.ican.domain.user.Resources;
import com.ican.domain.user.Role;
import com.ican.domain.user.RoleResources;
import com.ican.service.user.ResourcesService;
import com.ican.service.user.RoleService;
import com.ican.util.ContextUtils;
import com.opensymphony.xwork2.ActionSupport;

public class RoleAction extends ActionSupport {
    
    private static final long serialVersionUID = -7555806386280429294L;
    private static final Logger logger = LoggerFactory.getLogger(RoleAction.class);
    
    private RoleService roleService;
    private ResourcesService resourcesService;
    private Role role;
    private List<Resources> resourcesList;
    private Page<Role> page = new Page<Role>();
    private String paramsJson;
    private String resultJson;
    private String checkResIds;
    
    public String toAddRole(){
        return "add";
    }
    
    public String addRole(){
        if(role == null || StringUtils.isEmpty(role.getName())){
            ContextUtils.errorMsg2Session("角色名不能为空！");
            return "add";
        }
        try{
            roleService.addRole(role);
            role = null;
            ContextUtils.successMsg2Session(null);
            return list();
        }catch(BusinessException e){
            ContextUtils.errorMsg2Session(e.getMessage());
            logger.error(e.getMessage(),e);
            return "add";
        }catch(Exception e){
            ContextUtils.errorMsg2Session(null);
            logger.error(e.getMessage(),e);
            return "add";
        }
    }
    
    public String list(){
        try{
            page = roleService.findAllRole(page, role);
        }catch(BusinessException e){
            ContextUtils.errorMsg2Session(e.getMessage());
            logger.error(e.getMessage(),e);
        }catch(Exception e){
            ContextUtils.errorMsg2Session(null);
            logger.error(e.getMessage(),e);
        }
        return "list";
    }
    
    public String modifyRoleStatus(){
        try{
            roleService.modifyRoleStatus(role.getId(), role.getDataStatus());
            ContextUtils.successMsg2Session(null);
        }catch(BusinessException e){
            ContextUtils.errorMsg2Session(e.getMessage());
            logger.error(e.getMessage(),e);
        }catch(Exception e){
            ContextUtils.errorMsg2Session(null);
            logger.error(e.getMessage(),e);
        }
        return list();
    }
    
    public String toEditRole(){
        role = roleService.findRoleById(role.getId());
        return "edit";
    }
    
    public String editRole(){
        try{
            roleService.modifyRoleName(role);
            ContextUtils.successMsg2Session(null);
        }catch(BusinessException e){
            ContextUtils.errorMsg2Session(e.getMessage());
            logger.error(e.getMessage(),e);
        }catch(Exception e){
            ContextUtils.errorMsg2Session(null);
            logger.error(e.getMessage(),e);
        }
        return "edit";
    }
    
    public String roleResource(){
        try{
            resourcesList = resourcesService.findResourceByRoleId(role.getId());
            List<Integer> rids = new ArrayList<Integer>();
            for(Resources r : resourcesList){
                rids.add(r.getId());
            }
            //所有菜单
            resourcesList = resourcesService.getAllResource(0);
            StringBuffer sb = new StringBuffer();
            if(resourcesList != null && resourcesList.size() > 0){
                Resources r = null;
                sb.append("[");
                for(int i = 0; i < resourcesList.size(); i++){
                    r = resourcesList.get(i);
                    sb.append("{id:" + r.getId().toString() + ",");
                    if(r.getPid() == null){
                        sb.append("pId:0,");
                    }else{
                        sb.append("pId:" + r.getPid().intValue() + ",");
                    }
                    sb.append("name:\"" + r.getName() + "\",");
                    if(rids.contains(r.getId())){
                        sb.append("checked:true}");
                    }else{
                        sb.append("checked:false}");
                    }
                    if(i < resourcesList.size() - 1){
                        sb.append(",");
                    }
                }
                sb.append("]");
            }
            resultJson = sb.toString();
        }catch(BusinessException e){
            ContextUtils.errorMsg2Session(e.getMessage());
            logger.error(e.getMessage(),e);
        }catch(Exception e){
            ContextUtils.errorMsg2Session(null);
            logger.error(e.getMessage(),e);
        }
        return "resources";
    }

    public String modifyRoleResource(){
        try{
            if(checkResIds != null && checkResIds.length() > 0){
                //用户已经拥有的菜单
                resourcesList = resourcesService.findResourceByRoleId(role.getId());
                List<Integer> ridOld = new ArrayList<Integer>();
                for(Resources r : resourcesList){
                    ridOld.add(r.getId());
                }
                Integer id = null;
                for(String s : checkResIds.split(",")){
                    id = Integer.parseInt(s.trim());
                    if(id != 1){
                        if(ridOld.contains(id)){
                            roleService.removeRoleResources(new RoleResources(role.getId(), id));
                        }else{
                            roleService.addRoleResources(new RoleResources(role.getId(), id));
                        }
                    }
                }
            }
        }catch(BusinessException e){
            ContextUtils.errorMsg2Session(e.getMessage());
            logger.error(e.getMessage(),e);
        }catch(Exception e){
            ContextUtils.errorMsg2Session(null);
            logger.error(e.getMessage(),e);
        }
        return roleResource();
    }
    
    @Resource
    public void setResourcesService(ResourcesService resourcesService) {
        this.resourcesService = resourcesService;
    }
    @Resource
    public void setRoleService(RoleService roleService) {
        this.roleService = roleService;
    }
    public Role getRole() {
        return role;
    }
    public void setRole(Role role) {
        this.role = role;
    }
    public Page<Role> getPage() {
        return page;
    }
    public void setPage(Page<Role> page) {
        this.page = page;
    }
    public String getParamsJson() {
        return paramsJson;
    }
    public void setParamsJson(String paramsJson) {
        this.paramsJson = paramsJson;
    }
    public String getResultJson() {
        return resultJson;
    }
    public void setResultJson(String resultJson) {
        this.resultJson = resultJson;
    }
    public String getCheckResIds() {
        return checkResIds;
    }
    public void setCheckResIds(String checkResIds) {
        this.checkResIds = checkResIds;
    }

    public List<Resources> getResourcesList() {
        return resourcesList;
    }

    public void setResourcesList(List<Resources> resourcesList) {
        this.resourcesList = resourcesList;
    }
}
